package cn.tedu.boot2.utils;

import cn.tedu.boot2.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@Controller //声明Controller方法
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    //声明reg方法,调用User
    public String reg(User user) {
        System.out.println("user = " + user);
        //接受user数据

        try (Connection conn = DBUtils.getConn()) {
            String sql = "insert into user values(null,?,?,?)";
            //创建 插入sql语法
            PreparedStatement ps = conn.prepareStatement(sql);
            //替换 username,password,nick
            ps.setString(1,user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNick());
            ps.executeUpdate();
            //执行插入语句
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return "注册成功";
    }
    @RequestMapping("/login")
    @ResponseBody
    //创建login方法
    public String login(User user){
        System.out.println("user = " + user);
        //返回user数据
        try (Connection conn = DBUtils.getConn()){
            String sql = "select password from user where username=?";
            //创建查找数据的sql语句
            PreparedStatement ps = conn.prepareStatement(sql);
            //执行sql语句
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            //执行sql语句
            if (rs.next()){
                //拿用户输入的密码和数据库中查询到第一个密码比较
                if (user.getPassword().equals(rs.getString(1))){
                    //如果密码对上了
                    return "登录成功!";
                }
                //否则登陆失败
                return "密码错误!";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户名不存在!";
    }
}



